import 'package:dio/dio.dart';
import '../../services/user_utils.dart';
import '../../services/utils.dart';

class HeaderInterceptor implements Interceptor {
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    return handler.next(err);
  }

  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    // 设置Header
    final userAgent = await UserUtils.getUserAgent();

    // 获取token
    final token = await UserUtils.getToken();

    final now = DateTime.now();
    final timestamp = now.millisecondsSinceEpoch ~/ 1000;

    Map<String, String> dic = {
      'timestamp': '$timestamp',
      'ticket': "1111",
    };

    myLog("HeaderInterceptor dic = $dic");
    String encryptedStr = "eee";
    myLog("HeaderInterceptor encryptedStr = $encryptedStr");

    final newHeaders = Map<String, dynamic>.from(options.headers);
    newHeaders["User-Agent"] = userAgent;
    newHeaders["Accept-Language"] = "zh-Hans-CN;q=1, en-CN;q=0.9";
    newHeaders["Content-Type"] = "application/json";
    newHeaders["from-eai"] = "1";
    newHeaders["authorization-str"] = encryptedStr;

    // 添加Authorization请求头
    if (token != null && token.isNotEmpty) {
      newHeaders["Authorization"] = token; // 直接使用token，不加Bearer前缀
      myLog("HeaderInterceptor 添加Authorization: $token");
    } else {
      myLog("HeaderInterceptor 未找到token，跳过Authorization");
    }

    myLog("HeaderInterceptor newHeaders = ${newHeaders.toString()}");
    options.headers = newHeaders;
    return handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    return handler.next(response);
  }
}
